package com.dream.service.user.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.dream.common.model.response.BaseListResponse;
import com.dream.common.model.response.BaseResponse;
import com.dream.common.model.response.ErrorCode;
import com.dream.common.model.response.ListModel;
import com.dream.service.general.api.RegionServiceApi;
import com.dream.service.general.domain.model.City;
import com.dream.service.general.domain.model.Country;
import com.dream.service.user.api.StoreAddrService;
import com.dream.service.user.dao.StoreAddrDao;
import com.dream.service.user.domain.entity.Condition;
import com.dream.service.user.domain.model.StoreAddrModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 门店
 */
public class StoreAddrServiceImpl implements StoreAddrService {


    private StoreAddrDao storeAddrDao;

    private RegionServiceApi regionServiceApi;

    public StoreAddrDao getStoreAddrDao() {
        return storeAddrDao;
    }

    private Logger logger = LoggerFactory.getLogger(StoreAddrServiceImpl.class);

    @Autowired
    public void setStoreAddrDao(StoreAddrDao storeAddrDao) {
        this.storeAddrDao = storeAddrDao;
    }

    public RegionServiceApi getRegionServiceApi() {
        return regionServiceApi;
    }


    @Autowired
    public void setRegionServiceApi(RegionServiceApi regionServiceApi) {
        this.regionServiceApi = regionServiceApi;
    }

    @Override
    public BaseListResponse getStoreAddressList(String city) {
        long startTime = System.currentTimeMillis();
        if(StringUtils.isEmpty(city)){
            BaseListResponse baseListResponse= new BaseListResponse(ErrorCode.PARAM_ERROR);
            return baseListResponse;
        }
        BaseListResponse baseListResponse= new BaseListResponse();
        List<StoreAddrModel> userAddrModelList;
        try {
            userAddrModelList=storeAddrDao.selectByCityAndStatus(city,0);
            ListModel<List<StoreAddrModel>> listModel = new ListModel<List<StoreAddrModel>>();
            listModel.setList(userAddrModelList);
            baseListResponse.packData(true, ErrorCode.OK.getCode(), "", null, listModel);
        } catch (Exception e) {
            e.printStackTrace();
            baseListResponse.packData(false, ErrorCode.DB_ERROR.getCode(), e.getMessage(), null, null);
        }
        baseListResponse.setLatency(System.currentTimeMillis() - startTime);
        return baseListResponse;
    }

    @Override
    public BaseResponse<Boolean> addStoreAddress(StoreAddrModel storeAddrModel) {

        BaseResponse<Boolean> response = new BaseResponse<Boolean>();
        try {
            if (storeAddrModel == null) {
                response.packData(false, ErrorCode.PARAM_ERROR.getCode(), "unvalid param", null, null);
                return response;
            }
            String name = storeAddrModel.getName();
            String address = storeAddrModel.getAddress();
            Double lat = storeAddrModel.getLat();
            Double lng = storeAddrModel.getLng();
            if (StringUtils.isEmpty(name)) {
                response.packData(false, ErrorCode.PARAM_ERROR.getCode(), "please enter store name", null, null);
                return response;
            }
            if (StringUtils.isEmpty(address)) {
                response.packData(false, ErrorCode.PARAM_ERROR.getCode(), "please enter store address", null, null);
                return response;
            }
            if (lat == null || lng == null) {
                response.packData(false, ErrorCode.PARAM_ERROR.getCode(), "please enter store lat and lng", null, null);
                return response;
            }
            if(storeAddrModel.getType()==null){//如果没有类型
                storeAddrModel.setType(1);//默认设置为门店
            }
            BaseResponse<Country> cityInfo = regionServiceApi.createRelCity(lat, lng);
            if (cityInfo == null || cityInfo.getResult() == null) {
                logger.info("country is empty request:lat={},lng={},response={}", lat, lng, JSONObject.toJSON(response));
                response.packData(false, ErrorCode.BASE_SERVICE_ERROR.getCode(), "can not get country info", null, null);
                return response;
            }
            Country country = cityInfo.getResult();
            storeAddrModel.setCountry(country.getId());
            List<City> cityList = country.getCityList();
            if (cityInfo == null || cityList.isEmpty()) {
                logger.info("city is empyt;request:lat={},lng={},response={}", lat, lng, JSONObject.toJSON(response));
                response.packData(false, ErrorCode.BASE_SERVICE_ERROR.getCode(), "can not get city info", null, null);
                return response;
            }
            City city = cityList.get(0);
            Integer cityId = null;
            if (city != null) {
                cityId = city.getId();
                String cityName = city.getName();
                storeAddrModel.setCity(cityId);
                storeAddrModel.setCityName(cityName);
            } else {
                logger.info("get city empty for:{}", JSONObject.toJSONString(storeAddrModel));
                response.packData(false, ErrorCode.BASE_SERVICE_ERROR.getCode(), "can not get city info", null, null);
                return response;
            }
            try {
                List<StoreAddrModel> storeAddrModelList = storeAddrDao.selectByCityAndName(cityId.toString(), name);
                if (storeAddrModelList == null || storeAddrModelList.isEmpty()) {
                    Integer affect = storeAddrDao.addStoreAddress(storeAddrModel);
                    response.setSuccess(true);
                    response.setResult(affect != null && affect > 0);
                } else {
                    logger.info("has exist store,return now:{}", JSONObject.toJSON(storeAddrModel));
                    response.packData(false, ErrorCode.INVITE_CODE_INCORRECT.getCode(), "store has exits", null, null);
                }
            } catch (Exception e) {
                response.packData(false, ErrorCode.DB_ERROR.getCode(), e.getMessage(), null, null);
            }
            return response;
        }finally {
            logger.info("addStoreAddress request:{} response:{}",JSONObject.toJSONString(storeAddrModel),JSONObject.toJSONString(response));
        }
    }

    @Override
    public BaseResponse<StoreAddrModel> getStoreAddressById(Integer storeId) {
        BaseResponse<StoreAddrModel> response = new BaseResponse<StoreAddrModel>();
        if(storeId == null){
            response.packData(false,ErrorCode.PARAM_ERROR.getCode(),"storeId is null",null,null);
            return response;
        }
        StoreAddrModel storeAddrModel = storeAddrDao.selectById(storeId);
        response.setSuccess(true);
        response.setResult(storeAddrModel);
        return response;
    }

    @Override
    public BaseListResponse getStoreAddressByIds(List<Integer> storeIds) {
        BaseListResponse baseListResponse= new BaseListResponse(ErrorCode.PARAM_ERROR);
        if(CollectionUtils.isEmpty(storeIds)){
            baseListResponse.packData(false,ErrorCode.PARAM_ERROR.getCode(),"storeIds is null",null,null);
            return baseListResponse;
        }
        try {
            List<StoreAddrModel> storeAddrModelList = storeAddrDao.selectByIds(storeIds);
            ListModel<List<StoreAddrModel>> listModel = new ListModel<List<StoreAddrModel>>();
            listModel.setList(storeAddrModelList);

            baseListResponse.setSuccess(true);
            baseListResponse.setResult(listModel);
        }catch (Exception e){
            logger.error("getStoreAddressByIds process error:{}",e);
            baseListResponse.packData(false, ErrorCode.PROCESS_ERROR.getCode(), e.getMessage(), null, null);
        }
        return baseListResponse;
    }

    @Override
    public BaseListResponse getStoreAddressList(Condition condition) {
        long startTime = System.currentTimeMillis();
        if(condition == null){
            BaseListResponse baseListResponse= new BaseListResponse(ErrorCode.PARAM_ERROR);
            return baseListResponse;
        }
        int pageNum = 1;
        int pageSize = 10;
        if(condition.getPageNum() != null && condition.getPageNum() > 1){
            pageNum = condition.getPageNum();
        }

        if(condition.getPageSize() != null && condition.getPageSize() > 0){
            pageSize = condition.getPageSize();
        }
        condition.setPageNum(pageNum);
        condition.setPageSize(pageSize);
        condition.setStartNum((pageNum-1)*pageSize);
        BaseListResponse baseListResponse= new BaseListResponse();
        List<StoreAddrModel> userAddrModelList;
        try {
            userAddrModelList=storeAddrDao.selectByCondtion(condition);
            ListModel<List<StoreAddrModel>> listModel = new ListModel<List<StoreAddrModel>>();
            listModel.setList(userAddrModelList);
            Integer count =storeAddrDao.selectByCondtionCount(condition);
            if(count == null){
                count = 0;
            }
            listModel.setAmount(count);
            int pageAmout = 0;
            if(count>0) {
              pageAmout = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
            }
            listModel.setPageAmount(pageAmout);
            listModel.setCurrentPageNum(condition.getPageNum());
            listModel.setPageSize(condition.getPageSize());
            logger.info("store getStoreAddressList:{},count:{},request:{}",JSONObject.toJSONString(listModel),count,JSONObject.toJSONString(condition));
            baseListResponse.packData(true, ErrorCode.OK.getCode(), "", null, listModel);
        } catch (Exception e) {
            e.printStackTrace();
            baseListResponse.packData(false, ErrorCode.DB_ERROR.getCode(), e.getMessage(), null, null);
        }
        baseListResponse.setLatency(System.currentTimeMillis() - startTime);
        return baseListResponse;
    }

    @Override
    public BaseResponse<Integer> updateStoreAddress(StoreAddrModel storeAddrModel) {
        BaseResponse<Integer> response = new BaseResponse<Integer>();
        if(storeAddrModel == null  || storeAddrModel.getId() == null){
            response.packData(false,ErrorCode.PARAM_ERROR.getCode(),"unvalid param",null,null);
            return response;
        }
        try {
            logger.info("updateStoreAddress:{}",JSONObject.toJSONString(storeAddrModel));
            Integer affect = storeAddrDao.updateStoreAddress(storeAddrModel);
            response.packData(true, ErrorCode.OK.getCode(), "", null, affect);
        }catch (Exception e){
            logger.error("updateStoreAddress error,{}",e);
            response.packData(false, ErrorCode.DB_ERROR.getCode(), e.getMessage(), null, null);
        }
        return response;
    }

    @Override
    public BaseResponse<Boolean> delete(Integer storeId) {
       Integer affect = storeAddrDao.deleteStoreAddress(storeId);
        BaseResponse<Boolean> response = new BaseResponse<Boolean>();
        response.packData(true, ErrorCode.OK.getCode(), "", null, affect>0);
        return response;
    }

}
